<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">采购订单新建</p>
    </div>
    <div class="view-container">
      <el-row class="status-title">
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm(1)"
          >保存</el-button>
        </el-col>
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm(2)"
          >提交</el-button>
        </el-col>
        <!-- <el-col :span="10" class="status-container">
          <div class="status-item">
            <span class="active">草稿</span>
            <span>待审核</span>
            <span>已审核</span>
            <span>反审核</span>
          </div>
        </el-col> -->
      </el-row>
      <el-form ref="form" :model="form" label-width="140px" class="mt30">
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购订单编码:" prop="purchaseOrderCode">
              <el-input v-model="form.purchaseOrderCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务日期:" prop="businessDate">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.businessDate" suffix-icon="el-icon-date" type="date" placeholder="系统自动生成，获取当前日期时间" :picker-options="pickerOptions" style="width:100%;" :disabled="dataFlag" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商名称:" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请选择供应商" @focus="supplierShow" clearable @clear="supplierClear" />
              <!-- <el-autocomplete
                style="width: 100%;"
                v-model="form.supplierName"
                :fetch-suggestions="searchSupplierName"
                placeholder="请输入供应商名称"
                @select="val => selectSupplier(val)"
                clearable
              >
                <el-button slot="append" @click="toSupplier">
                  <img src="../../../assets/img/ew.png" class="icon-image" />
                </el-button>
              </el-autocomplete> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务部门:" prop="businessUnit">
              <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择">
                <el-option
                  v-for="item in unitList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="到货日期:" prop="arrivalDate">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.arrivalDate" suffix-icon="el-icon-date" type="datetime" placeholder="采购期望日期" :picker-options="pickerOptions" style="width:100%;" @change="onChangeDate" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票类型:" prop="invoiceType">
              <el-select v-model="form.invoiceType" style="width:100%;" placeholder="请选择">
                <el-option
                  v-for="item in invoiceTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务模式:" prop="businessModel">
              <el-select v-model="form.businessModel" style="width:100%;" placeholder="请选择">
                <el-option
                  v-for="item in modelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="8">
            <el-form-item label="上传附件:">
              <el-upload
                action="#"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-change="onUploadType"
                :auto-upload="false"
                multiple
                :limit="3"
                :on-exceed="onExceed"
                :file-list="fileList"
                ref="fileUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="form.remark" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="productData">
              <el-table-column label="序号" type="index" align="center" width="50" />
              <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                <template slot-scope="scope">
                  <template v-if="item.type == '1'">
                    <el-input v-model="scope.row[item.prop]" placeholder="请选择产品" @focus="productShow" />
                    <!-- <el-autocomplete
                      style="width:74%;margin-right:5px;"
                      v-model="scope.row[item.prop]"
                      :fetch-suggestions="searchCode"
                      placeholder="请输入产品编码"
                      @select="val => handleSelect(val, scope.row, scope.$index)"
                    ></el-autocomplete>
                    <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku"></el-button> -->
                  </template>
                  <template v-if="item.type == '2'">
                    <el-input v-model="scope.row[item.prop]" placeholder="请选择产品" @focus="productShow"/>
                    <!-- <el-autocomplete
                      style="width:74%;margin-right:5px;"
                      v-model="scope.row[item.prop]"
                      :fetch-suggestions="searchName"
                      placeholder="请输入产品名称"
                      @select="val => handleSelect(val, scope.row, scope.$index)"
                    ></el-autocomplete>
                    <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku"></el-button> -->
                  </template>
                  <template v-if="item.type == '3'">{{ scope.row[item.prop] }}</template>
                  <template v-if="item.type == 'num'">
                    <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                  </template>
                  <template v-if="item.type == 'untaxedAmount'">
                    <el-input placeholder="请输入未税价格" v-model="scope.row[item.prop]" @input="(val) => inputUntaxedAmount(val, scope.row)" v-if="scope.row.priceType == '0'" />
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                  <template v-if="item.type == 'taxUnitPrice'">
                    <el-input placeholder="请输入含税价格" v-model="scope.row[item.prop]" @input="(val) => inputTaxUnitPrice(val, scope.row)" v-if="scope.row.priceType == '1'" />
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                  <template v-if="item.type == 'taxRate'">
                    <el-input placeholder="请输入税率" v-model="scope.row[item.prop]" @input="inputTaxRate(scope.row)" />
                  </template>
                  <template v-if="item.type == 'batch'">
                    <template v-if="scope.row.enableBatches == '0'">
                      <el-input v-model="scope.row[item.prop]" placeholder="请输入批次号" />
                    </template>
                    <template v-else>
                      <el-input placeholder="未启用批次" disabled />
                    </template>
                  </template>
                  <template v-if="item.type == 'gift'">
                    <el-checkbox v-model="scope.row[item.prop]"></el-checkbox>
                  </template>
                  <template v-if="item.type == 'date'">
                    <el-date-picker value-format="yyyy-MM-dd" v-model="scope.row[item.prop]" suffix-icon="el-icon-date" type="date" placeholder="到货日期" :picker-options="pickerOptions" style="width:100%;"></el-date-picker>
                  </template>
                  <template v-if="item.type == '4'">
                    <el-select v-model="scope.row[item.prop]" style="width:100%;" placeholder="请选择">
                      <el-option
                        v-for="item in warehouseList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                  <template v-if="item.type == '5'">
                    <el-input placeholder="备注" v-model="scope.row[item.prop]" />
                  </template>
                  <span class="del" v-if="item.type == 'del'" @click="deleteRow(scope.row, scope.$index)">删除</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row class="mt20">
          <el-col :span="8">
            <el-form-item label="合计数量:" prop="totalNum">
              <el-input v-model="form.totalNum" placeholder="系统自动合计" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计未税金额:" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="系统自动合计" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计价税合计:" prop="totalTaxAmount">
              <el-input v-model="form.totalTaxAmount" placeholder="系统自动合计" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 弹出数据 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" top="50px" append-to-body center :before-close="handleClose">
      <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
        <el-form-item :label="label" prop="searchValue">
          <el-input
            v-model="queryParams.searchValue"
            placeholder="请输入名称或编码检索"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="dataList" @row-click="onSelectData" :default-sort="{prop: 'date', order: 'descending'}" border>
        <el-table-column label="序号" type="index" align="center" width="50">
           <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <template v-if="type == '1'">
          <el-table-column label="编号" align="center" prop="supCode" :show-overflow-tooltip="true" sortable />
          <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"  width="300" />
          <el-table-column label="纳税比例类型" align="center" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              {{ scope.row.shareInvoice.taxpayerScale == '0' ? '13%' : scope.row.shareInvoice.taxpayerScale == '1' ? '9%' : scope.row.shareInvoice.taxpayerScale == '2' ? '6%' : scope.row.shareInvoice.taxpayerScale == '3' ? '3%' : scope.row.shareInvoice.taxpayerScale == '4' ? '1%' : '' }}
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="approveStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.approveStatus == 0" style="color:#13C2C2">待审核</div>
              <div v-if="scope.row.approveStatus == 1" style="color:#13C2C2">已审核</div>
              <div v-if="scope.row.approveStatus == 3" style="color:#fd562c">拒绝</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <div v-if="scope.row.status == 2" style="color:#13C2C2">禁用</div>
              <div v-if="scope.row.status == 1" style="color:#52C41A">正常</div>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        </template>
        <template v-if="type == '2'">
          <el-table-column label="SKU编码" align="center" prop="specificationCode" :show-overflow-tooltip="true" width="150" sortable />
          <el-table-column label="SKU名称" align="center" prop="specificationName" :show-overflow-tooltip="true" width="250" />
          <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
          <el-table-column label="是否启用扫码" align="center" prop="isSerial" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.isSerial == '0'" style="color:#13C2C2">启用</div>
              <div v-if="scope.row.isSerial == '1'" style="color:#52C41A">禁用</div>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="approvalStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus == 0" style="color:#13C2C2">草稿</div>
              <div v-if="scope.row.approvalStatus == 1" style="color:#13C2C2">待审核</div>
              <div v-if="scope.row.approvalStatus == 2" style="color:#52C41A">已审核</div>
              <div v-if="scope.row.approvalStatus == 3" style="color:#fd562c">拒绝</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="productStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.productStatus == 0" style="color:#13C2C2">禁用</div>
              <div v-if="scope.row.productStatus == 1" style="color:#52C41A">正常</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { orderAdd, orderEdit, orderDetail, delProduct } from "@/api/system/purchaseOrder/order"
import { listProduct, listSupplier} from "@/api/system/basicdata/basicdata"
import { uploadImg } from "@/api/system/upload/upload"
export default {
  name: "orderAdd",
  data(){
    return {
      form: {
        purchaseOrderCode: '', // 采购订单编码
        businessDate: '', // 业务日期
        supplierName: '', // 供应商名称
        supplierInfoId: '', // 供应商id
        arrivalDate: '', // 到货日期
        businessModel: '现金采购', // 业务模式
        businessUnit: '采购部', // 业务部门
        invoiceType: '普通发票', // 发票类型
        remark: '', // 备注
        purchaseOrderProductList: [], // 商品数据
        totalNum: '', // 合计数量
        totalAmount: '', // 合计未税金额
        totalTaxAmount: '', // 合计价税合计
        taxRate: '', // 税率
        shareFiles: [], // 附件
      },
      dataFlag: true, // 业务日期disabled控制
      arrivalDate: '', // 到货日期
      // 业务模式
      modelList: [
        {
          value: '现金采购'
        },
        {
          value: '赊购'
        }
      ],
      // 业务部门
      unitList: [
        {
          value: '采购部'
        },
        {
          value: '销售部'
        }
      ],
      // 发票类型
      invoiceTypeList: [
        {
          value: '普通发票'
        },
        {
          value: '增值税发票'
        },
        {
          value: '收据'
        }
      ],
      // 日期控制
      pickerOptions: {
        // disabledDate(time) {
        //   return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        // }
      },
      // 表头
      columns: [{
        prop: "productBasicCode",
        label: "产品编码",
        width: 160,
        type: '1'
      },{
        prop: "productBasicName",
        label: "产品名称",
        width: 200,
        type: '2'
      },{
        prop: "productCode",
        label: "sku编码",
        width: 160,
        type: '1'
      },{
        prop: "productName",
        label: "sku名称",
        width: 200,
        type: '2'
      },{
        prop: "specification",
        label: "规格",
        width: 100,
        type: '3'
      },{
        prop: "batch",
        label: "批次",
        width: 150,
        type: 'batch'
      },{
        prop: "num",
        label: "数量",
        width: 120,
        type: 'num'
      },{
        prop: "unit",
        label: "单位",
        width: 100,
        type: '3'
      },{
        prop: "arrivalDate",
        label: "预计到货日期",
        width: 160,
        type: 'date'
      },{
        prop: "untaxedAmount",
        label: "未税单价",
        width: 100,
        type: 'untaxedAmount'
      },{
        prop: "taxUnitPrice",
        label: "含税单价",
        width: 100,
        type: 'taxUnitPrice'
      },{
        prop: "amount",
        label: "未税金额",
        width: 120,
        type: '3'
      },{
        prop: "taxRate",
        label: "税率(%)",
        width: 80,
        type: 'taxRate'
      },{
        prop: "levy",
        label: "税款",
        width: 100,
        type: '3'
      },{
        prop: "totalTax",
        label: "价税合计",
        width: 120,
        type: '3'
      },{
        prop: "isGift",
        label: "赠品",
        width: 80,
        type: 'gift'
      },
      // {
      //   prop: "requisitionNumber",
      //   label: "关联申请单号",
      //   width: 100,
      //   type: '3'
      // },
      // {
      //   prop: "warehouseCount",
      //   label: "实际入库",
      //   width: 100,
      //   type: '3'
      // },
      {
        prop: "remark",
        label: "备注",
        width: 200,
        type: '5'
      },{
        label: "",
        type: 'del',
        width: 80
      }],
      // 表格数据
      productData: [
        // {
        //   productId: '', // 产品Id
        //   productCode: '', // 产品编码
        //   productName: '', // 产品名称
        //   productShortName: '', // 货品简称
        //   specification: '', // 规格
        //   batch: '', // 批次
        //   num: '', // 数量
        //   unit: '', // 单位
        //   priceType: '', // 价格类型
        //   untaxedAmount: '', // 未税单价
        //   taxUnitPrice: '', // 含税单价
        //   amount: '', // 金额
        //   taxRate: '', // 税率
        //   levy: '', // 税款
        //   totalTax: '', // 价税合计
        //   isGift: '', // 赠品
        //   arrivalDate: '', // 到货日期
        //   requisitionNumber: '', // 关联申请单号
        //   warehouseCount: '', // 实际入库
        //   storeId: '', //
        //   enableBatches: '', // 是否启用批次
        //   remark: ''
        // }
      ],
      id: '',
      open: false,
      type: '',
      title: '',
      label: '',
      loading: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined
      },
      // 弹出数据列表
      dataList: [],
      // 供应商列表
      // searchSupplierList: [],
      // 产品数据
      // searchProduct: [],
      // 供应商
      // supplier: {},
      fileList: []
    }
  },
  methods: {
    // 获取详情信息
    getDetailData() {
      orderDetail(this.id).then(res => {
        this.form = res.data
        if(res.data.purchaseOrderProductList == null){
          this.productData = []
        }else{
          res.data.purchaseOrderProductList.forEach(item => {
            if(item.isGift == '1'){
              item.isGift = true
            }else{
              item.isGift = false
            }
          })
          this.productData = res.data.purchaseOrderProductList
        }
        this.addProduct()
      })
    },
    // 供应商数据显示
    supplierShow(){
      this.open = true
      this.title = '供应商'
      this.label = '供应商名称'
      this.type = '1'
      this.dataList = []
      this.getList()
    },
    // 删除供应商
    supplierClear(){
      this.form.supplierName = ''
      this.form.supplierInfoId = ''
      this.form.taxRate = ''
      this.productData = []
      this.totalData()
    },
    // 产品数据显示
    productShow(){
      if(this.form.supplierName !== ''){
        this.open = true
        this.title = '产品'
        this.label = '产品名称'
        this.type = '2'
        this.dataList = []
        this.getList()
      }else{
        this.$modal.msgError('请选择供应商！')
      }
    },
    // 获取弹窗数据
    getList(){
      if(this.type == '1'){
        this.loading = true
        this.queryParams.approveStatus = 1
        this.queryParams.status = 1
        listSupplier(this.addDateRange(this.queryParams)).then(res => {
          this.dataList = res.rows
          this.total = res.total
          this.loading = false
        })
      }else if(this.type == '2'){
        this.loading = true
        this.queryParams.approvalStatus = 2
        this.queryParams.productStatus = 1
        // this.queryParams.productProperties = 1
        listProduct(this.addDateRange(this.queryParams)).then(res => {
          this.dataList = res.rows
          this.total = res.total
          this.loading = false
        })
      }
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 选中数据
    onSelectData(row){
      if(this.type == '1'){
        // 供应商选择
        if(this.form.supplierName !== row.name){
          this.form.supplierName = row.name
          this.form.supplierInfoId = row.id
          this.form.taxRate = row.shareInvoice == null ? '' : row.shareInvoice.taxpayerScale == '0' ? '13' : row.shareInvoice.taxpayerScale == '1' ? '9' : row.shareInvoice.taxpayerScale == '2' ? '6' : row.shareInvoice.taxpayerScale == '3' ? '3' : row.shareInvoice.taxpayerScale == '4' ? '1' : ''
          this.productData = []
          this.totalData()
          this.addProduct()
        }else{
          this.$modal.msgError('供应商已存在，请重新选择！')
        }
      }else if(this.type == '2'){
        // 产品选择
        let price = row.purchasePrice !== null ? row.purchasePrice : 0
        let obj = ''
        if(row.priceType == '1'){
          obj = {
            productBasicId: row.productId, // 产品Id
            productBasicCode: row.productCode, // 产品编码
            productBasicName: row.productName, // 产品名称
            productId: row.productSpecificationsId, // sku产品Id
            productCode: row.specificationCode, // sku产品编码
            productName: row.specificationName, // sku产品名称
            productShortName: row.shortName, // 货品简称
            specification: row.value1 + row.value2, // 规格
            num: '', // 数量
            priceType: row.priceType, // 价格类型
            unit: row.unit, // 单位
            taxRate: this.form.taxRate, // 税率
            untaxedAmount: (price / (1 + (Number(this.form.taxRate) / 100))).toFixed(2), // 未税单价
            taxUnitPrice: price, // 含税单价
            amount: '', // 金额
            levy: '', // 税款
            totalTax: '', // 价税合计
            isGift: '', // 赠品
            arrivalDate: '', // 到货日期
            requisitionNumber: '', // 关联申请单号
            warehouseCount: '', // 实际入库
            enableBatches: row.enableBatches, // 是否启用批次
            remark: '', // 备注
          }
        }else{
          obj = {
            productBasicId: row.productId, // 产品Id
            productBasicCode: row.productCode, // 产品编码
            productBasicName: row.productName, // 产品名称
            productId: row.productSpecificationsId, // sku产品Id
            productCode: row.specificationCode, // sku产品编码
            productName: row.specificationName, // sku产品名称
            productShortName: row.shortName, // 货品简称
            specification: row.value1 + row.value2, // 规格
            num: '', // 数量
            priceType: row.priceType, // 价格类型
            unit: row.unit, // 单位
            taxRate: this.form.taxRate, // 税率
            untaxedAmount: price, // 未税单价
            taxUnitPrice: (price * (1 + (Number(this.form.taxRate) / 100))).toFixed(2), // 含税单价
            amount: '', // 金额
            levy: '', // 税款
            totalTax: '', // 价税合计
            isGift: '', // 赠品
            arrivalDate: '', // 到货日期
            requisitionNumber: '', // 关联申请单号
            warehouseCount: '', // 实际入库
            enableBatches: row.enableBatches, // 是否启用批次
            remark: '', // 备注
          }
        }
        if(this.productData.length == 0){
          this.productData.push(obj)
        }else{
          let index = this.productData.findIndex(item => item.productCode == row.specificationCode)
          if(index > -1){
            this.$modal.msgError('产品已存在，请重新选择！')
          }else{
            this.productData.push(obj)
          }
        }
        let arr = this.productData.filter(item => item.productCode !== '')
        this.productData = arr
        this.addProduct()
      }
      this.open = false
      this.title = ''
      this.label = ''
      this.type = ''
      this.queryParams.searchValue = undefined
      this.queryParams.productStatus = undefined
      this.queryParams.approvalStatus = undefined
      this.queryParams.approveStatus = undefined
      this.queryParams.status = undefined
      this.handleQuery()
      this.dataList = []
    },
    // 关闭弹窗
    handleClose(){
      this.open = false
      this.title = ''
      this.label = ''
      this.type = ''
      this.queryParams.searchValue = undefined
      this.queryParams.productStatus = undefined
      this.queryParams.approvalStatus = undefined
      this.queryParams.approveStatus = undefined
      this.queryParams.status = undefined
      this.handleQuery()
      this.dataList = []
    },
    // 获取供应商
    // getListSupplier(){
    //   listSupplier(this.addDateRange({status: 1, approvalStatus: 1})).then(res => {
    //     this.searchSupplierList = res.rows
    //   })
    // },
    // 供应商名称搜索
    // searchSupplierName(val, cb){
    //   let list = []
    //   this.searchSupplierList.map(item => {
    //     list.push(Object.assign(
    //       {},item,{
    //         value: item.name
    //       }
    //     ))
    //   })
    //   var arr = list
    //   var results = val ? arr.filter(this.createFilter(val)) : arr
    //   cb(results)
    // },
    // 匹配
    // createFilter(val) {
    //   return (res) => {
    //     return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
    //   }
    // },
    // 选中供应商
    // selectSupplier(e){
    //   this.supplier = e
    //   this.form.supplierName = e.name
    //   this.form.supplierInfoId = e.id
    //   this.form.taxRate = e.shareInvoice == null ? '' : e.shareInvoice.taxpayerScale == '0' ? '13' : e.shareInvoice.taxpayerScale == '1' ? '9' : e.shareInvoice.taxpayerScale == '2' ? '6' : e.shareInvoice.taxpayerScale == '3' ? '3' : e.shareInvoice.taxpayerScale == '4' ? '1' : ''
    //   if(this.productData.length > 1){
    //     this.$modal.msgError('供应商已更改，请重新选择产品！')
    //     this.form.totalNum = 0
    //     this.form.totalAmount = 0
    //     this.productData = []
    //     this.addProduct()
    //   }
    // },
    // 跳转供应商列表
    // toSupplier(){
    //   this.$router.push({path:"/basicData/supplier", query:{ type: '1' }})
    // },
    // 到货日期选中
    // onChangeDate(e){
    //   this.arrivalDate = e
    // },
    // 获取产品信息
    // getSearchProduct(){
    //   listProduct({approvalStatus: 2, productStatus: 1}).then(res => {
    //     this.searchProduct = res.rows
    //   })
    // },
    // 跳转产品分类搜索sku
    // searchProductSku(){
    //   if(this.form.supplierName !== ''){
    //     // if(this.form.taxRate !== ''){
    //       let arr = this.productData.filter(item => item.productCode !== '')
    //       this.$router.push({path:"/basicData/product/sortList", query:{ type: '1', supplier: this.supplier, productData: arr }})
    //     // }else{
    //     //   this.$modal.msgError('选中供应商信息不完整，请重新选择！')
    //     // }
    //   }else{
    //     this.$modal.msgError('请选择供应商！')
    //   }
    // },
    // 商品编码搜索
    // searchCode(val, cb) {
    //   let list = []
    //   this.searchProduct.map(item => {
    //     list.push(Object.assign(
    //       {},item,{
    //         value: item.specificationCode
    //       }
    //     ))
    //   })
    //   var arr = list
    //   var results = val ? arr.filter(this.createFilter(val)) : arr
    //   cb(results)
    // },
    // 商品名称搜索
    // searchName(val, cb){
    //   let list = []
    //   this.searchProduct.map(item => {
    //     list.push(Object.assign(
    //       {},item,{
    //         value: item.specificationName
    //       }
    //     ))
    //   })
    //   var arr = list
    //   var results = val ? arr.filter(this.createFilter(val)) : arr
    //   cb(results)
    // },
    // // 匹配
    // createFilter(val) {
    //   return (res) => {
    //     return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
    //   }
    // },
    // 选中
    // handleSelect(item, row, index){
    //   // console.log(item)
    //   if(this.form.supplierName !== ''){
    //       row.productId = item.productSpecificationsId // skuId
    //       row.productCode = item.specificationCode // sku编码
    //       row.productName = item.specificationName // sku名称
    //       row.productShortName = item.shortName // 简称
    //       row.specification = item.value1 + item.value2 // 规格
    //       row.unit = item.unit // 单位
    //       row.taxRate = this.form.taxRate // 税率
    //       row.priceType = item.priceType // 价格类型
    //       row.num = ''
    //       row.amount = '' // 金额
    //       row.levy = '' // 税款
    //       row.totalTax = '' // 价税合计
    //       // let str = this.form.taxRate.substring(0, this.form.taxRate.lastIndexOf('%'))
    //       // // console.log(str)
    //       // 判断价格类型 1 含税价格 0 未税价格
    //       if(item.priceType == '1'){
    //         row.taxUnitPrice = item.purchasePrice !== null ? item.purchasePrice : 0 // 含税单价
    //         row.untaxedAmount = (row.taxUnitPrice / (1 + (Number(this.form.taxRate) / 100))).toFixed(2) // 未税单价
    //       }else{
    //         row.untaxedAmount = item.purchasePrice !== null ? item.purchasePrice : 0 // 未税单价
    //         row.taxUnitPrice = (row.untaxedAmount * (1 + (Number(this.form.taxRate) / 100))).toFixed(2) // 含税单价
    //       }
    //       row.arrivalDate = this.arrivalDate ? this.arrivalDate : ''
    //       row.enableBatches = item.enableBatches
    //       // // 判断编码是否重复
    //       let arr = this.productData.filter(item => item.productCode !== '')
    //       if(arr && arr.length > 0){
    //           let productCode = arr.map(i => i.productCode)
    //           let productCodeSet = new Set(productCode)
    //           if(productCodeSet.size == productCode.length){
    //             this.productData = arr
    //             this.addProduct()
    //             this.totalData()
    //           }else{
    //             this.$modal.msgError('产品已存在，请重新选择！')
    //             this.productData.splice(index, 1)
    //             let newArr = this.productData.filter(item => item.productCode !== '')
    //             this.productData = newArr
    //             this.addProduct()
    //             this.totalData()
    //           }
    //       }
    //   }else{
    //     this.$modal.msgError('请选择供应商！')
    //     this.productData = []
    //     this.addProduct()
    //   }
    // },
    // 批次号验证
    // onChangeBatch(val){
    //   if(val == ''){
    //     this.$modal.msgError('批次号不能为空!')
    //   }
    // },
    // 数量验证
    inputNum(val, row){
      if(val == '' || val == undefined){
        this.$modal.msgError('数量不能为空!')
        row.num = ''
        row.amount = ''
        row.totalTax = ''
        row.levy = ''
        this.form.totalNum = 0
        this.form.totalAmount = 0
      }else{
        if(/^[1-9]\d*$|^0$/.test(val) == false){
          this.$modal.msgError('数量必须是数字！')
          row.num = ''
          row.amount = ''
          row.totalTax = ''
          row.levy = ''
          this.form.totalNum = 0
          this.form.totalAmount = 0
          return false
        }else{
          if(JSON.parse(val) <= 0){
            this.$modal.msgError('数量必须大于0!')
            row.num = ''
          }else{
            row.amount = (val * row.untaxedAmount).toFixed(2) // 未税金额
            row.totalTax = (val * row.taxUnitPrice).toFixed(2) // 价税合计
            row.levy = (row.totalTax - row.amount).toFixed(2) // 税额
            this.totalData()
          }
        }
      }
    },
    // 未税单价
    inputUntaxedAmount(val, row){
      if(val == '' || val == undefined){
        this.$modal.msgError('价格不能为空!')
        row.untaxedAmount = ''
        row.taxUnitPrice = ''
        row.amount = ''
        row.totalTax = ''
        row.levy = ''
        this.form.totalNum = 0
        this.form.totalAmount = 0
      }else{
        // if(/^[1-9]\d*$|^0$/.test(val) == false){
        if(/^(([1-9]{1}\d*)|(0{1}))((.\d{0,2})?)$/.test(val) == false){
          this.$modal.msgError('请输入正确的价格！')
          row.untaxedAmount = ''
          row.taxUnitPrice = ''
          row.amount = ''
          row.totalTax = ''
          row.levy = ''
          return false
        }else {
          // if(val <= 0){
          //   this.$modal.msgError('价格必须大于0!')
          //   row.untaxedAmount = ''
          //   row.taxUnitPrice = ''
          // }else{
            // let str = row.taxRate.substring(0, row.taxRate.lastIndexOf('%'))
            row.taxUnitPrice = (row.untaxedAmount * (1 + (Number(row.taxRate) / 100))).toFixed(2) // 含税单价
            if(row.num !== ''){
              row.amount = (val * row.num).toFixed(2) // 未税金额
              row.totalTax = (row.num * row.taxUnitPrice).toFixed(2) // 价税合计
              // row.levy = ((row.totalTax / (1 + (Number(str) / 100))) * (Number(str) / 100)).toFixed(2) // 税额
              row.levy = (row.totalTax - row.amount).toFixed(2) // 税额
              this.totalData()
            }
          // }
        }
      }
    },
    // 含税价格
    inputTaxUnitPrice(val, row){
      if(val == '' || val == undefined){
        this.$modal.msgError('含税价格不能为空!')
        row.untaxedAmount = ''
        row.taxUnitPrice = ''
        row.amount = ''
        row.totalTax = ''
        row.levy = ''
        this.form.totalNum = 0
        this.form.totalAmount = 0
      }else{
        // if(/^[1-9]\d*$|^0$/.test(val) == false){
        if(/^(([1-9]{1}\d*)|(0{1}))((.\d{0,2})?)$/.test(val) == false){
          this.$modal.msgError('请输入正确的含税价格！')
          row.untaxedAmount = ''
          row.taxUnitPrice = ''
          row.amount = ''
          row.totalTax = ''
          row.levy = ''
          return false
        }else {
          // if(val <= 0){
          //   this.$modal.msgError('含税价格必须大于0!')
          //   row.untaxedAmount = ''
          //   row.taxUnitPrice = ''
          // }else{
            // let str = row.taxRate.substring(0, row.taxRate.lastIndexOf('%'))
            row.untaxedAmount = (Number(val) / (1 + (Number(row.taxRate) / 100))).toFixed(2) // 未税单价
            if(row.num !== ''){
              row.amount = (row.untaxedAmount * row.num).toFixed(2) // 未税金额
              row.totalTax = (row.num * row.taxUnitPrice).toFixed(2) // 价税合计
              row.levy = (row.totalTax - row.amount).toFixed(2) // 税额
              this.totalData()
            }
          // }
        }
      }
    },
    // 税率
    inputTaxRate(row){
      // 判断价格类型 1 含税价格 0 未税价格
      if(row.priceType == '0'){
        row.taxUnitPrice = (row.untaxedAmount * (1 + (Number(row.taxRate) / 100))).toFixed(2) // 含税单价
      }else{
        row.untaxedAmount = (Number(row.taxUnitPrice) / (1 + (Number(row.taxRate) / 100))).toFixed(2) // 未税单价
      }
      row.amount = (row.untaxedAmount * row.num).toFixed(2) // 未税金额
      row.totalTax = (row.num * row.taxUnitPrice).toFixed(2) // 价税合计
      row.levy = (row.totalTax - row.amount).toFixed(2) // 税额
    },
    // 添加一条产品信息
    addProduct(){
      let data = {
        key: {
          purchaseOrderId: this.id ? this.id : '',
          productId: ''
        }
      }
      this.columns.forEach(item =>{
        data.key[item.prop] = ''
      })
      this.productData.push(JSON.parse(JSON.stringify(data.key)))
    },
    // 删除数据
    deleteRow(item, index){
      if(item.productId !== ''){
        this.$modal.confirm('是否确认删除当前数据？', '删除').then(() => {
          if(item.id && item.id !== '' || item.id !== undefined){
            delProduct(item.id).then(res => {
              // console.log(res)
              if(res.code == 200){
                this.getDetailData()
                this.totalData()
              }
            })
          }else{
            this.productData.splice(index, 1)
            this.totalData()
          }
        }).catch(() => {})
      }else{
        this.$modal.msgError('最少保留一条可编辑数据！')
      }
    },
    // 合计
    totalData(){
      let totalNum = 0
      let totalAmount = 0
      let totalTaxAmount = 0
      this.productData.forEach(item => {
          totalNum += Number(item.num)
          totalAmount += Number(item.amount)
          totalTaxAmount += Number(item.totalTax)
          return (totalNum, totalAmount, totalTaxAmount)
      })
      this.form.totalNum = totalNum
      this.form.totalAmount = totalAmount.toFixed(2)
      this.form.totalTaxAmount = totalTaxAmount.toFixed(2)
    },
    // 上传附件
    onUploadType(item){
      this.$modal.loading("正在上传")
      let formData = new FormData()
      let file = item.raw
      formData.append('file', file)
      uploadImg(formData).then(res => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess("上传成功")
        let obj = {
          name: res.data.fileName,
          url: res.data.fileUrl
        }
        this.fileList.push(obj)
        this.form.shareFiles.push(res.data)
      })
    },
    handleRemove(item) {
      const a = this.fileList.findIndex(i => i.name == item.name)
      this.fileList.splice(a, 1)
      const idx = this.form.shareFiles.findIndex(i => i.fileName == item.name)
      this.form.shareFiles.splice(idx, 1)
    },
    onExceed() {
      this.$modal.msgError('图片上传不能超过9张!')
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${ file.name }？`)
    },
    // 提交数据
    submitForm(e) {
      // console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 过滤掉空数据
          let arr = this.productData.filter(item => item.productCode !== '')
          arr.forEach(item => {
            if(item.isGift == true){
              item.isGift = 1
            }else{
              item.isGift = 0
            }
          })
          let num = arr.every(val => !!val.num)
          let untaxedAmount = arr.every(val => !!val.untaxedAmount)
          let enableBatches = arr.every(val => {
            if(val.enableBatches == '0'){
              return !!val.batch
            }else{
              return !val.batch
            }
          })
          this.form.purchaseOrderProductList = arr
          if(e == 1){
            // 保存
            if(this.id){
              let arr = this.form
              arr.id = this.id
              this.$modal.loading("正在保存")
              orderEdit(arr).then(res=> {
                if(res.code == 200){
                  this.$modal.closeLoading()
                  this.getDetailData()
                  this.$modal.msgSuccess("保存成功")
                }
              })
            }else{
              this.$modal.loading("正在保存") 
              orderAdd(this.form).then(res=> {
                if(res.code == 200){
                  this.$modal.closeLoading()  
                  this.id = res.data.id
                  this.getDetailData()
                  this.$modal.msgSuccess("保存成功")
                }
              })
            }
          }else{
            if(arr.length > 0){
              if(num == true){
                if(untaxedAmount == true){
                  if(enableBatches == true){
                    // 提交
                    if(this.id){
                      let arr = this.form
                      arr.id = this.id
                      arr.approvalStatus = 0
                      arr.status = 1
                      this.$modal.loading("正在提交")
                      orderEdit(arr).then(res=> {
                        if(res.code == 200){
                          this.$refs.form.resetFields()
                          this.$tab.closeOpenPage({ path: "/purchase/purchaseOrder/list" })
                          this.$modal.msgSuccess("新建成功")
                          this.$modal.closeLoading()
                        }
                      })
                    }else{
                      let arr = this.form
                      arr.approvalStatus = 0
                      arr.status = 1
                      this.$modal.loading("正在提交")
                      orderAdd(arr).then(res=> {
                        if(res.code == 200){
                          this.$modal.closeLoading()
                          this.$refs.form.resetFields()
                          this.$tab.closeOpenPage({ path: "/purchase/purchaseOrder/list" })
                          this.$modal.msgSuccess("新建成功")
                        }
                      })
                    }
                  }else{
                    this.$modal.msgError('批次不能为空！')
                  }
                }else{
                  this.$modal.msgError('未税单价不能为空，产品信息不完善！')
                }
              }else{
                this.$modal.msgError('产品数量不能为空！')
              }
            }else{
              this.$modal.msgError('请选择产品！')
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.del{
  color: #ff0000;
  cursor: pointer;
}
</style>
